import {fileURLToPath, URL} from 'node:url'

import {defineConfig, loadEnv} from 'vite'
import vue from '@vitejs/plugin-vue'
import vueDevTools from 'vite-plugin-vue-devtools'
import path from 'path'
import {Dates} from './src/util/dates'

export default defineConfig(({mode}) => {
    const envDir = path.resolve(__dirname, 'resource')
    //加载环境文件(.env)
    const env = loadEnv(mode, envDir, '')
    return {
        plugins: [
            vue(),
            //开发时才启用vueDevTools插件
            mode === 'dev' ? vueDevTools() : null
        ].filter(Boolean),
        envDir,
        resolve: {
            //设置路径别名
            alias: {
                '@': fileURLToPath(new URL('./src', import.meta.url))
            },
        },
        server: {
            host: env.VITE_APP_HOST,
            port: Number(env.VITE_APP_PORT),
            open: true,
        },
        preview: {
            host: env.VITE_APP_HOST,
            port: Number(env.VITE_APP_PORT),
            open: true,
        },
        build: {
            //打包后产生文件夹的名称
            outDir: env.VITE_APP_NAME,
            //每次构建清空旧目录
            emptyOutDir: true,
            //打包时不输出gzip大小
            reportCompressedSize: false,
            //只在开发环境打sourcemap
            sourcemap: mode === 'dev',
            //拆包
            rollupOptions: {
                output: {
                    manualChunks: {
                        vue: ['vue', 'vue-router', 'pinia'],
                        vendor: ['axios']
                    }
                }
            }
        },
        //一些全局宏
        define: {
            __APP_ENV__: JSON.stringify(mode),
            __BUILD_TIME__: JSON.stringify(Dates.now()),
        }
    }
})
